import './UI.ts';


//金字塔(我终于愿意写了 2025/07/18)
// 胜利区域
let winZone = world.addZone({
  selector: "*",
  bounds: new GameBounds3(
    new GameVector3(550.9, 1.2, 580.7),
    new GameVector3(557.8, 11.6, 589.4)
  ),
});

winZone.onEnter(async ({ entity: blockWinner }) => {
  // 进入胜利区域时的逻辑
  if (
    !blockWinner ||
    (!blockWinner.id.endsWith("的线") && !blockWinner.hasTag?.("block"))
  ) return
  // 防止多次触发
  if (blockWinner._winHandled) return;
  blockWinner._winHandled = true;
  // 立即禁用碰撞和重力
  blockWinner.collides = false;
  blockWinner.gravity = false;
  world.querySelectorAll("player").forEach(async (player) => {
    if (player.block && player.block.id === blockWinner.id) {
      player.cameraTargeting = null
      player.control = false;
      player.cloning = true;
      player.collides = true;
      player.fixed = true;
      player.Jump = true;
      blockWinner.meshOrientation = new GameQuaternion(0.0, 0.383, 0.0, 0.926);
      player.player.colorLUT = "lut/Night1.lut";
      player.player.cameraEntity = null;
      // 终点动画
      // 显示胜利对话框，点击后传送
      await player.player.dialog({
        type: GameDialogType.SELECT,
        title: `胜利`,
        content: `完成关卡！\n100%`,
        options: ["返回大厅"],
      });
      try {
        await world.teleport("100459168", [player]);
      } catch (e: any) {
        world.say("传送失败：" + e.stack);
      }
    }
  });
});

//隐藏引导线
world.onPlayerJoin(async ({ entity }) => {
  const followLine = await entity.player.dialog({
    type: GameDialogType.SELECT,
    title: `欢迎`,
    content: `点击空格(跳跃键)开始游戏，如果开始了就可以转向\n是否开启引导线？`,
    options: ["开启", "关闭"],
  });
  if (!followLine) {
    world.querySelectorAll("*").forEach((entity) => {
      if (entity.id.startsWith("引导线")) {
        entity.meshInvisible = false;
      }
    });
    return;
  }
  if (followLine.value === "关闭") {
    world.querySelectorAll("*").forEach((entity) => {
      if (entity.id.startsWith("引导线")) {
        entity.meshInvisible = true;
      }
    });
  } else if (followLine.value === "开启") {
    world.querySelectorAll("*").forEach((entity) => {
      if (entity.id.startsWith("引导线")) {
        entity.meshInvisible = false;
      }
    });
  }
});
world.querySelectorAll("*").forEach((entity) => {
  if (entity.id.startsWith("引导线")) {
    entity.meshInvisible = true;
  }
});

//游戏参数
let BEGINNING_TIME = 79.257;

// 摄像机偏移到玩家方块实体正后上方
const CAMERA_OFFSET = new GameVector3(-1.4, 20, -20); // 正后上方

// 初始化所有非玩家实体
world.querySelectorAll("*").forEach((entity) => {
  if (!entity.player) {
    entity.fixedPosition = entity.position.clone();
    entity.fixedScale = entity.meshScale;
    entity.fixedCollides = entity.collides;
    entity.fixedFixed = entity.fixed;
    if (entity.id.startsWith("正方形赛道")) {
      entity.collides = true;
      entity.fixed = true;
    }
  }
});

world.onPlayerJoin(async ({ entity }) => {
  entity.death = false;
  // entity.player.colorLUT = 'lut/Filmic6.lut'
  entity.player.disableInputDirection = GameInputDirection.BOTH;
  entity.control = true;
  entity.cloning = false;
  entity.clicking = 0;
  entity.block = world.createEntity({
    mesh: "mesh/方块-序幕.vb",
    position: new GameVector3(0, 3, 0),
    meshScale: new GameVector3(0.05, 0.05, 0.05),
    collides: true,
    fixed: false,
    gravity: true,
  });
  entity.block.id = `${entity.player.name}的线`;
  entity.block.addTag("block");
  entity.block.showEntityName = true;
  entity.player.canFly = false;
  entity.player.enableAction0 = false;
  entity.player.enableAction1 = false;
  entity.player.enableCrouch = false;
  entity.player.enableDoubleJump = false;
  if (entity.cameraTargeting !== null) {
    entity.player.cameraMode = GameCameraMode.FIXED;
    entity.player.cameraPosition = new GameVector3(
      entity.block.position.x + CAMERA_OFFSET.x,
      entity.block.position.y + CAMERA_OFFSET.y,
      entity.block.position.z + CAMERA_OFFSET.z
    );
    entity.player.cameraTarget = entity.block.position.clone();
  }
  entity.Jump = false;
  entity.player.invisible = true;
  entity.player.showName = false;
  entity.player.spectator = false;
  entity.going = "z";
  entity.player.cameraEntity = entity.block;
  entity.player.cameraFovY = 80.5;
  while (1) {
    entity.progress += 0.5;
    await sleep(500);
  }
});

world.onPress(async ({ button, entity }) => {
  if (button === GameButtonType.JUMP && entity.control) {
    if (entity.Jump == false) {
      entity.progress = 0;
      entity.cloning = true;
      entity.Jump = true;
      await sleep(2000);
      entity.player.music.sample = "audio/Cheetah Mobile - 时钟 The Clock.mp3";
    } else {
      if (entity.going === "x") {
        entity.going = "z";
      } else if (entity.going == "z") {
        entity.going = "x";
      }
    }
    // console.log('第' + entity.clicking + '次点击，坐标:(' + Math.floor(entity.block.position.x * 100) / 100 + ', ' + Math.floor(entity.block.position.y * 100) / 100 + ', ' + Math.floor(entity.block.position.z * 100) / 100 + ')')
    entity.clicking += 1;
  }
});

world.onTick(() => {
  world.querySelectorAll("player").forEach(async (e) => {
    e.alwaysPercent = `${Math.ceil((e.progress / BEGINNING_TIME) * 100)}%`;
    if (e.alwaysPercent == `60%`) {
      console.log('60%')
    }
    if (e.Jump) {
      if (e.going === "x") {
        e.block.position.x += 1;
      } else if (e.going === "z") {
        e.block.position.z += 1;
      }
      if (e.block.position.y <= 3) {
        e.control = false;
        e.percent = `${Math.ceil((e.progress / BEGINNING_TIME) * 100)}%`;
        e.cloning = false;
      }
      if (e.block.position.y <= -6) {
        e.Jump = false;
        e.death = true;
        e.player.colorLUT = "lut/Night1.lut";
        await e.player.dialog({
          type: GameDialogType.SELECT,
          title: `失败`,
          content: `失败！\n当前进度\n${e.percent}\n[当前Demo暂不支持复活]`,
          options: ["重新开始"],
        });
        world.querySelectorAll("*").forEach(async (e) => {
          if (!e.player) {
            e.fixedPosition = e.position.clone();
            e.fixedScale = e.meshScale;
            e.fixedCollides = e.collides;
            e.fixedFixed = e.fixed;
            if (e.id.startsWith("跳舞的线-界外")) {
              e.collides = true;
              e.fixed = true;
            }
          }
        });
        e.going = "z";
        e.progress = 0;
        e.player.colorLUT = "";
        e.player.music.sample = "";
        e.control = true;
        e.block.destroy();
        e.cloning = false;
        e.clicking = 0;
        e.block = world.createEntity({
          mesh: "mesh/方块-序幕.vb",
          position: new GameVector3(0, 3, 0),
          meshScale: new GameVector3(0.05, 0.05, 0.05),
          collides: true,
          fixed: false,
          gravity: true,
        });
        if (e.cameraTargeting !== null) {
          e.player.cameraPosition = new GameVector3(
            e.block.position.x + CAMERA_OFFSET.x,
            e.block.position.y + CAMERA_OFFSET.y,
            e.block.position.z + CAMERA_OFFSET.z
          );
          e.player.cameraTarget = e.block.position.clone();
        }
        e.block.id = e.player.name;
        e.block.addTag("block");
        e.block.showEntityName = true;
        e.death = false;
        world.querySelectorAll(`.${e.player.userId}`).forEach(async (e1) => {
          for (let i = 0; i <= 10; i++) {
            await sleep(10);
          }
          e1.destroy();
        });
      }
      if (e.cloning) {
        if (e.cameraTargeting !== null) {
          e.player.cameraPosition = new GameVector3(
            e.block.position.x + CAMERA_OFFSET.x,
            e.block.position.y + CAMERA_OFFSET.y,
            e.block.position.z + CAMERA_OFFSET.z
          );
          e.player.cameraTarget = e.block.position.clone();
        }
        let block_body = world.createEntity({
          id: "block_body",
          position: e.block.position.clone(),
          meshScale: new GameVector3(0.00000001, 0.00000001, 0.00000001),
          collides: false,
          fixed: true,
          gravity: false,
        });
        if (!block_body) return;
        block_body.addTag(e.player.userId);
        block_body.mesh = "mesh/方块-序幕.vb";
        await sleep(125);
        block_body.meshScale = new GameVector3(0.05, 0.05, 0.05);
        await sleep(10000); // 克隆体存在时间加长
        if (e.death === false) {
          block_body.destroy();
        }
      }
    }
  });
});
